import { PrismaClient } from "@prisma/client";
import { NextApiRequest, NextApiResponse } from "next";
import { get } from "@/utils/_";
import dayjs from "dayjs";
import { v4 } from "uuid";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  const prisma = new PrismaClient();
  const body = JSON.parse(req.body);

  const client = JSON.parse(decodeURIComponent(req.cookies.user as string));

  const article = await prisma.article.upsert({
    where: {
      id: body?.id || v4(),
    },
    create: {
      userId: client.id,
      title: body.title,
      content: body.content,
      tags: {
        connect: get(body, "tags", []).map((i: number) => ({ id: i })),
      },
      public: Boolean(body.public),
      year: dayjs().year(),
    },
    update: {
      title: body.title,
      content: body.content,
      tags: {
        set: get(body, "tags", []).map((i: number) => ({ id: i })),
      },
      public: Boolean(body.public),
      year: dayjs().year(),
    },
  });

  return res.json(article);
}
